package cn.edu.xmu.oomall.comment.controller;

import cn.edu.xmu.javaee.core.aop.Audit;
import cn.edu.xmu.javaee.core.aop.LoginUser;
import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.Constants;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.model.ReturnObject;
import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.javaee.core.model.vo.PageVo;
import cn.edu.xmu.javaee.core.validation.NewGroup;
import cn.edu.xmu.oomall.comment.controller.dto.CommentDto;
import cn.edu.xmu.oomall.comment.controller.vo.CommentVo;
import cn.edu.xmu.oomall.comment.dao.bo.Comment;
import cn.edu.xmu.oomall.comment.service.CommentService;
import lombok.RequiredArgsConstructor;
import cn.edu.xmu.javaee.core.util.CloneFactory;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;


@RestController /*Restful的Controller对象*/
@RequestMapping(produces = "application/json;charset=UTF-8")
@Transactional
@RequiredArgsConstructor
public class CustomerCommentController {
    private final static Logger logger = LoggerFactory.getLogger(CustomerCommentController.class);
    private final CommentService commentService;

    /**
     * 顾客新增评论
     * @param oid 订单明细id
     * @param user 用户
     * @param dto 评论信息
     * @return 评论对象
     */
    @PostMapping("/customers/orderItems/{oid}/comments")
    @Audit(departName = "comments")
    public ReturnObject createComment(@PathVariable Long oid,
                                      @Validated(NewGroup.class) @RequestBody CommentDto dto,
                                      @LoginUser UserDto user) {
        Comment mainComment = CloneFactory.copy(new Comment(), dto);
        mainComment.setOrderItemId(oid);
        Comment comment = commentService.createComment(mainComment, user);
        return new ReturnObject(ReturnNo.CREATED, CloneFactory.copy(new CommentVo(comment), comment));
    }


    /**
     * 查看评论
     * @param id 商品id
     * @return 评论列表
     */
    @GetMapping("/products/{id}/comments")
    @Audit(departName = "comments")
    public ReturnObject getCommentsByProductId(@PathVariable Long id,
                                               @RequestParam(required = false, defaultValue = "1") Integer page,
                                               @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        List<Comment> commentList = commentService.findCommentsByProductId(id, page, pageSize);
        return new ReturnObject(ReturnNo.OK, new PageVo<>(commentList.stream().map(o -> CloneFactory.copy(new CommentVo(o), o)).toList(), page, pageSize));
    }



}
